package com.lan.app.utils;

import com.alibaba.fastjson.JSON;
import com.lan.ot.ClazzOt;
import com.lan.util.TypeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtils {


    /**
     * @return
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * @return
     */
    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getResponse();
    }


    public static Object get(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String v = request.getParameter(key);
        return TypeUtils.strTo(v);
    }

    public static ClazzOt getJson(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }

        HttpServletRequest request = getRequest();
        String body = request.getParameter(key);
        if (StringUtils.isBlank(body)) {
            return null;
        }
        Object o = JSON.parse(body);
        ClazzOt ot = new ClazzOt(o);
        return ot;
    }


    public static String getUrl() {
        HttpServletRequest request = getRequest();
        return request.getRequestURI();
    }

}
